package com.yutel.phone.xplayer.service;

import java.net.InetAddress;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.yutel.phone.xplayer.ui.AirplayNotifier;
import com.yutel.phone.xplayer.utils.CommonUtil;
import com.yutel.silver.vo.Device;

public class AirplayService extends Service {
	private static final String TAG = "AirplayService";
	private int port = 8888;
	private String name = "Doudian";
	android.net.wifi.WifiManager.MulticastLock lock;
	private AikaServer aika;
	private Device mDevice;
	private AirplayNotifier airplayNotifier;

	@Override
	public void onCreate() {
		Log.d(TAG, "onCreate()");
		airplayNotifier=AirplayNotifier.getInstance(this);
		mDevice = new Device();
		mDevice.setDeviceid("58:55:CA:1A:E2:88");
		mDevice.setFeatures("119");
		mDevice.setModel("AppleTV2,1");
		mDevice.setProtovers("1.0");
		mDevice.setSrcvers("120.2");
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		start();
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		if (aika != null) {
			aika.stop();
			airplayNotifier.setMessage("airplay service stoped!");
			airplayNotifier.updateNotification();
			lock.release();
		}
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	private void start() {
		android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
		lock = wifi.createMulticastLock("mylockthereturn");
		lock.setReferenceCounted(true);
		lock.acquire();
		try {
			InetAddress ia = CommonUtil.getAddress();
			if (ia != null) {
				airplayNotifier.setMessage("airplay service starting!");
				airplayNotifier.updateNotification();
				aika = AikaServer.getInstance(mDevice, ia, port, name);
				aika.setContext(getApplicationContext());
				aika.start();
				airplayNotifier.setMessage("airplay service started!");
				airplayNotifier.updateNotification();
			} else {
				Log.e(TAG, "get ip adderss error!");
			}
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			return;
		}
	}
}
